package com.bcqn.controller;

import com.bcqn.common.CommonResponse;
import com.bcqn.service.MiniProgramService;
import com.bcqn.service.UserService;
import com.bcqn.utils.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.bcqn.utils.MiniProgramUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/common")
public class CommonController {
    @Resource
    private MiniProgramService miniProgramService;

    @Resource
    private UserService userService;

    @PostMapping("/getImgKey")
    public CommonResponse generatorImgKey(@RequestParam("filePrefix") String filePrefix, @RequestParam("file") MultipartFile file) throws Exception {
        validateImg(file);
        String key = FileUtil.upload(filePrefix + "/" + System.currentTimeMillis() + Objects.requireNonNull(file.getOriginalFilename()).replace(';', '\0').replace('/', '\0'), file.getInputStream());
        Map<String, Object> map = new HashMap<>();
        map.put("imgUrl", key);
        return CommonResponse.success(map);
    }

    @PostMapping("/getImgKeys")
    public CommonResponse generatorImgKeys(@RequestParam("filePrefix") String filePrefix, @RequestParam("files") MultipartFile[] files) throws Exception {
        StringBuilder keys = new StringBuilder("");
        for (MultipartFile file : files) {
            validateImg(file);
            String key = FileUtil.upload(filePrefix + "/" + System.currentTimeMillis() + Objects.requireNonNull(file.getOriginalFilename()).replace(';', '\0').replace('/', '\0'), file.getInputStream());
            keys.append(key).append(";");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("imgUrl", keys.toString());
        return CommonResponse.success(map);
    }

    @GetMapping("/test")
    public CommonResponse Test() {
        return CommonResponse.success("test");
    }

    private void validateImg(MultipartFile files) {
        if (files == null) {
            throw new RuntimeException("图片不能为空");
        }
        if (files.getSize() >= 20 * 1024 * 1024) {
            throw new RuntimeException("图片大小超出最大限制");
        }
        boolean isPic = FileUtil.isPic(files.getOriginalFilename());
        if (!isPic) {
            throw new RuntimeException("图片格式错误");
        }
    }

    public String getOpenId(HttpServletRequest request) {
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if ("_login_token".equals(cookie.getName())) {
//                return AESUtil.decode(cookie.getValue());
//            }
//        }
//        return null;
        //mock阶段全部返回111111111
        return "111111111";
    }

    public Long getUserId(){
        return userService.getUserByOpenid("111111111").getUserId();
    }


    @PostMapping("/getWxaCodeUnlimit")
    public CommonResponse getWxaCodeUnlimit(@RequestBody  String body) throws Exception {
        String accessToken = "";
        // TODO appid secret 配置化
        // TODO 直接使用 String accessToken = miniProgramService.getAccessToken();
        JSONObject jsonObject = MiniProgramUtil.getAccessToken("wx9d6eeca62a08180b","eb6036e6730c79c32195103e6ee51ca5");
        if (StringUtils.isBlank(jsonObject.getString("access_token"))) {
            return CommonResponse.fail("获取小程序access_token出错："+jsonObject.getString("errmsg"));
        } else {
            accessToken = jsonObject.getString("access_token");
        }
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

        String encode = "";

        HttpPost httppost = new HttpPost(url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        StringEntity se = new StringEntity(body, "UTF-8");
        httppost.setEntity(se);
        CloseableHttpResponse response = httpclient.execute(httppost);
        try
        {
            HttpEntity entity = response.getEntity();
            if (entity != null)
            {
                byte[] b = EntityUtils.toByteArray(entity);
                encode = Base64.encodeBase64String(b);
            }
        }
        finally
        {
            response.close();
        }
        httpclient.close();

        // TODO 暴露错误码
        return CommonResponse.success(encode);
    }
}